<template>
  <header>
    <div class="search-reture" @click="goBack">
      <i class="iconfont icon-fanhui"></i>
    </div>
    <div class="search-main">
      <i class="iconfont icon-Magnifier"></i>
      <form action="" onsubmit="return false" @keyup.enter="goSearch">
        <input type="search" placeholder="搜索您喜欢的产品..." v-model="searchValue"/>
      </form>
    </div>
    <div class="search-btn" @click="goSearch">搜索</div>
  </header>
</template>

<script>
export default {
  data() {
    return {
      searchValue:this.$route.query.keyWord||'',
      searchArr:[]
    }
  },
  methods:{
    // 返回
    goBack(){
      this.$router.back()
    },
    goSearch(){
      // 搜索关键字为空直接返回
      if(!this.searchValue) return;
      // 判断之前搜索有没有本地存储,没有就创建一个
      if(!localStorage.getItem('searchList')){
        // 没有
        localStorage.setItem('searchList','[]')
      }else{
        // 有
        this.searchArr=JSON.parse(localStorage.getItem('searchList'))
      }
      // 添加数据
      this.searchArr.unshift(this.searchValue)
      // //ES6的set去重
      let newArr = new Set(this.searchArr); 
      // // 给本地存储进行赋值
      localStorage.setItem('searchList',JSON.stringify(Array.from(newArr)))
      // 判断搜索的关键词是否一致，一致就不进行路由的跳转
      if(this.searchValue == this.$route.query.keyWord) return
      // 把搜索词给query参数之后进行跳转
      this.$router.push({name:'goods',query:{keyWord:this.searchValue}})
    }
  }

};
</script>
<style scoped lang="scss">
header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 1.173333rem;
  color: #fff;
  background-color: #b0352f;
}
.search-reture {
  padding: 0 0.266667rem;
  i {
    font-size: 0.746667rem;
  }
}
.search-main {
  display: flex;
  align-items: center;
  width: 6.933333rem;
  height: 0.8rem;
  border-radius: 0.32rem;
  background-color: #fff;
  i {
    padding: 0 0.266667rem;
    color: #000;
  }
  form {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    input {
      width: 100%;
    }
  }
}
.search-btn {
  padding: 0 0.266667rem;
  font-size: 0.426667rem;
}
</style>